//
//  JPChatViewController.m
//  聊天界面
//
//  Created by 周述坚 on 16/11/12.
//  Copyright © 2016年 周述坚. All rights reserved.
//

#import "JPChatViewController.h"
#import "JPMessageCell.h"
#import "JPMessageModel.h"
#import "JPMessageFrame.h"

#define width self.view.bounds.size.width
#define heigth self.view.bounds.size.height

@interface JPChatViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (strong,nonatomic)UITableView *tableView;

@property (strong,nonatomic)UITextField *text;

@property (strong, nonatomic)NSDictionary *outReplay;

@property (strong,nonatomic)NSMutableArray *msgArr;

@end

@implementation JPChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.text.delegate = self;
    
    // 去掉分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 预估行高
    self.tableView.estimatedRowHeight = 50;
    self.tableView.backgroundColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1];
    // 订阅文本输入框点击后键盘弹出事件
    // 获取通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self selector:@selector(didClickKeyBoradFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    self.navigationItem.title = @"美女护士为您服务";
    
    UIButton *liftButton = [[UIButton alloc] init];
    liftButton.frame = CGRectMake(0, 0, 40, 40);
    [liftButton setTitle:@"返回" forState:UIControlStateNormal];
    [liftButton addTarget:self action:@selector(didClickReturnButton) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *liftItem = [[UIBarButtonItem alloc] initWithCustomView:liftButton];
    self.navigationItem.leftBarButtonItem = liftItem;
    
}

- (void)didClickReturnButton {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"嘿,帅哥不聊了?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"嗯咯" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"那再聊会吧" style:UIAlertActionStyleCancel handler:nil]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

/**
 *  搭建界面
 */
- (void)setupUI {
    
    // 搭建滚动视图
    CGFloat viewX = 0;
    CGFloat viewY = 0;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(viewX, viewY, width, heigth-50) style: UITableViewStylePlain];
    
    [self.view addSubview:_tableView];
    
    // 搭建对话框
    UIView *dialog = [[UIView alloc] initWithFrame:CGRectMake(0, heigth-50, width, 50)];
    UIImageView *dialogView = [[UIImageView alloc] init];
    dialogView.frame = CGRectMake(0, 0, width, dialog.bounds.size.height);
    dialogView.image = [UIImage imageNamed:@"chat_bottom_bg"];
    [dialog addSubview:dialogView];
    [self.view addSubview:dialog];
    dialogView.userInteractionEnabled = YES;
    
    // 对话框左边视图
    UIImageView *left = [UIImageView new];
    left.frame = CGRectMake(8, 8, 40, 40);
    left.image = [UIImage imageNamed:@"chat_bottom_voice_nor"];
    [dialogView addSubview:left];
    
    // 中间微笑视图
    UIImageView *smile = [UIImageView new];
    smile.frame = CGRectMake(width-120, 8, 40, 40);
    smile.image = [UIImage imageNamed:@"chat_bottom_smile_nor"];
    [dialogView addSubview:smile];
    
    // 右边视图
    UIImageView *right = [UIImageView new];
    right.frame = CGRectMake(width-60, 8, 40, 40);
    right.image = [UIImage imageNamed:@"chat_bottom_up_nor"];
    [dialogView addSubview:right];
    
    self.text = [[UITextField alloc] initWithFrame:CGRectMake(60, 8, 220, 34)];
    self.text.borderStyle = UITextBorderStyleRoundedRect;
    self.text.keyboardType = UIKeyboardTypeDefault;
    self.text.keyboardAppearance = UIReturnKeySend;
    self.text.returnKeyType = UIReturnKeySend;
    [dialogView addSubview:self.text];
}

#pragma mark - 懒加载
- (NSMutableArray*)msgArr {
    if (_msgArr == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"messages" ofType:@"plist"];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *arrM = [NSMutableArray new];
        for (NSDictionary *dic in arr) {
            JPMessageModel *msgM = [JPMessageModel messageModelWithDic:dic];
            JPMessageFrame *lastF = [arrM lastObject];
            if ([lastF.msgM.time isEqualToString:msgM.time]) {
                msgM.hiddenTime = YES;
            } else {
                msgM.hiddenTime = NO;
            }
            JPMessageFrame *msgF = [JPMessageFrame new];
            msgF.msgM = msgM;
            [arrM addObject:msgF];
        }
        _msgArr = arrM;
    }
    return _msgArr;
}

- (NSDictionary*)outReply {
    if (_outReplay == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"auto_reply" ofType:@"plist"];
        _outReplay = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    return _outReplay;
}

/**
 *  设置行高
 */
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    JPMessageFrame *mf = self.msgArr[indexPath.row];
    return mf.rowH;
}


#pragma mark tableView dataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JPMessageCell *cell = [JPMessageCell messageCellWithTableView:tableView];
    cell.msgF = self.msgArr[indexPath.row];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.msgArr.count;
}

// 当选中table时,执行的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 结束编辑状态,收回键盘
    [self.view endEditing:YES];
}
/**
 *  开始拖拽TableView时调用的方法
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    // 结束编辑状态,收回键盘
    [self.view endEditing:YES];
}

/**
 *  监控文本输入框输入后点击发送按钮的方法
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    // 发送消息后,将这个文本信息存入消息实例数组
    [self addMessageWithType:MessageTypeMe andText:self.text.text];
    NSString *reply = @"我不明白你的意思";
    for (NSString *key in self.outReply) {
        if ([self.text.text containsString:key]) {
            reply = self.outReply[key];
            break;
        }
    }
    [self addMessageWithType:MessageTypeOther andText:reply];
    [self.tableView reloadData];
    // 让tableView往上滚
    NSIndexPath *idxPath = [NSIndexPath indexPathForRow:self.msgArr.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:idxPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    // 按下发送信息后,清空文本输入框
    self.text.text = nil;
    return YES;
}

/**
 *  输入一条信息后,存入消息实例数组中
 */
-(void)addMessageWithType:(MessageType)type andText:(NSString*)text {
    JPMessageModel *msgMod =[JPMessageModel new];
    msgMod.type = type;
    msgMod.text = text;
    
    NSDate *time = [NSDate new];
    NSDateFormatter *fmt = [NSDateFormatter new];
    fmt.dateFormat = @"HH:mm";
    msgMod.time =[fmt stringFromDate:time];
    
    JPMessageFrame *lastOb = self.msgArr.lastObject;
    if ([msgMod.time isEqualToString:lastOb.msgM.time]) {
        msgMod.hiddenTime = YES;
    }
    JPMessageFrame *msgFrm =[JPMessageFrame new];
    msgFrm.msgM = msgMod;
    [self.msgArr addObject:msgFrm];
}

- (void)didClickKeyBoradFrame:(NSNotification *)no {
    // 获取动画时长
    CGFloat time = [no.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    // 获取键盘滚动完成之后的frame
    CGRect endFrame = [no.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 获取self.View的Y值
    CGFloat viewY = endFrame.origin.y - self.view.frame.size.height;
    
    [UIView animateWithDuration:time animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, viewY);
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
